package com.lagou.niancheng.lagouservicecode.service;

import com.lagou.niancheng.lagou.service.common.EmailApi;
import com.lagou.niancheng.lagou.service.common.EmailDTO;
import com.lagou.niancheng.lagou.service.common.LagouException;
import com.lagou.niancheng.lagouservicecode.common.CodeErrorCode;
import com.lagou.niancheng.lagouservicecode.common.entity.CodeDO;
import com.lagou.niancheng.lagouservicecode.dao.CodeDAO;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;


@Service
public class CodeServiceImpl implements CodeService {

    @Value("${lagou.niancheng.code.expire.secs:600}")
    private Integer expireSecs;

    @Reference
    private EmailApi emailApi;

    @Resource
    private CodeDAO codeDAO;
    private Random random = new Random();

    @Override
    public void generateVerifyCode(String email) {
        String code = getCode();
        CodeDO codeDO = new CodeDO();
        codeDO.setCode(code);
        codeDO.setCreateTime(new Date());
        codeDO.setEmail(email);
        codeDO.setExpireTime(getExpireTime());
        codeDAO.insertCode(codeDO);
        EmailDTO emailDTO = new EmailDTO();
        emailDTO.setCode(code);
        emailDTO.setEmail(email);
        // 发送验证码到邮件
        emailApi.sendMail(emailDTO).check();
    }


    private String getCode() {
        int codeLength = 6;
        char[] result = new char[codeLength];
        for (int i = 0; i < codeLength; i++) {
            result[i] = (char) (random.nextInt(9) + '0');
        }
        return new String(result);
    }

    private Date getExpireTime() {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, expireSecs);
        return instance.getTime();
    }

    @Override
    public boolean checkVerifyCode(String email, String verifyCode) {
        CodeDO codeDO = codeDAO.getByCode(verifyCode);
        if (codeDO == null) {
            throw new LagouException(CodeErrorCode.NO_THIS_CODE);
        }
        if (System.currentTimeMillis() > codeDO.getExpireTime().getTime()) {
            throw new LagouException(CodeErrorCode.CODE_EXPIRE);
        }
        return true;
    }
}
